package logic

import (
	"context"
	"fmt"
	"novel/model/mysql"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 作品列表展示
func (l *BookListLogic) BookList(in *novelrpc.BookListRequest) (*novelrpc.BookListResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Where("id=?", in.UserId).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	offset := (in.Page - 1) * in.Size
	var book []mysql.BookList
	tx := mysql.DB.Table("books").
		Select("books.*,users.nick_name,users.image").
		Joins(" LEFT JOIN users ON users.id = books.user_id").
		Offset(int(offset)).Limit(int(in.Size)).Order("created_at desc")

	if in.Title != "" {
		tx.Where("title like ?", "%"+in.Title+"%")
	}
	if in.Types != "" {
		tx.Where("types like ?", "%"+in.Types+"%")
	}
	tx.Find(&book)

	var bookList []*novelrpc.BookList
	for _, m := range book {
		list := novelrpc.BookList{
			Title:    m.Title,
			Types:    m.Types,
			Label:    m.Label,
			Text:     m.Text,
			Image:    m.Image,
			NickName: m.NickName,
		}
		bookList = append(bookList, &list)
	}
	return &novelrpc.BookListResponse{
		List: bookList,
	}, nil
}
